<template>
  <div class="biaoge">
    <!-- 页面头部标题 -->
    <div class="head">考场管理</div>
    
  <el-tabs type="border-card">
    <el-tab-pane label="试卷信息" v-model="activeName">
       <!-- 搜索表单 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <!-- 试卷名称搜索框 -->
      <el-input v-model="saosuo.xianguan" placeholder="请输入试卷名称" />
      
      <!-- 试卷类型下拉框 -->
      <el-form-item>
        <el-select-v2
          v-model="saosuo.leibie"
          :options="initials"
          placeholder="选择试卷类型"
          clearable
        />
      </el-form-item>
      
      <!-- 搜索按钮 -->
      <el-button type="primary" class="search-button" @click="performSearch">搜索</el-button>
    </el-form>
    
    <!-- 试卷表格 -->
    <el-table :data="tableData" style="width: 120%;">
      <!-- 试卷名称列 -->
      <el-table-column prop="examination_name" label="试卷名称" align="center" width="180"  sortable/>
      
      <!-- 试卷类型列 -->
      <el-table-column prop="direction_name" label="试卷类型" align="center" width="180" />
      
      <!-- 总分列 -->
      <el-table-column prop="examination_score" label="总分" align="center" width="180" />
      
      <!-- 编辑时间列 -->
      <el-table-column prop="examination_time" label="编辑时间" align="center" width="180" sortable>
        <template #default="scope">
          <!-- 格式化显示编辑时间 -->
          {{ formattedCreateTime(scope.row.examination_time) }}
        </template>
      </el-table-column>
      
      <!-- 编辑人列 -->
      <el-table-column prop="nick_name" label="编辑人" align="center" width="180" />
      
      <!-- 操作列 -->
      <el-table-column label="操作" align="center" width="230">
        <template #default="scope">
          <!-- 编辑按钮 -->
          <el-button plain type="danger" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          
          <!-- 预览按钮 -->
          <el-button plain type="warning" size="small" @click="handleLook(scope.$index, scope.row)">预览</el-button>
          
          <!-- 创建按钮 -->
          <el-button plain type="success" size="small" @click="handlePreview(scope.$index, scope.row)">创建</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="saosuo.pageNum"
        v-model:page-size="saosuo.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="saosuo.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: center;"
    />
    </el-tab-pane>

      <!--考试表单-->
          <el-tab-pane label="考试信息">
      <el-table :data="tableData02" style="width: 100%">
        <el-table-column prop="exam_name" label="考场名称" width="180" />
        <el-table-column prop="examination_name" label="试卷名称" width="180" />
        
        <el-table-column prop="direction_name" label="试卷类型" width="180" />
        <el-table-column prop="start_time" label="开始时间" width="180" sortable >
            <template #default="scope">
          <!-- 格式化显示编辑时间 -->
          {{ formattedCreateTime2(scope.row.start_time) }}
        </template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" width="180"  sortable>
              <template #default="scope">
          <!-- 格式化显示编辑时间 -->
          {{ formattedCreateTime2(scope.row.end_time) }}
        </template>
        </el-table-column>
        

         <el-table-column prop="address" label="操作"  >
            <template #default="scope">
              <el-button plain type="warning" size="small" @click="bianji(scope.$index, scope.row)"  :class="!scope.row.hasResult?'button2':'button1'">编辑</el-button>
              <el-button plain type="danger" size="small" @click="delexam(scope.$index, scope.row)"  :class="!scope.row.hasResult?'button2':'button1'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      <!-- 分页组件 -->
    <el-pagination
          v-model:current-page="saosuo02.pageNum"
          v-model:page-size="saosuo02.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="zongshuxx"
          @size-change="handleSizeChange02"
          @current-change="handleCurrentChange02"
          style="margin-top: 20px; justify-content: center;"
        />
      </el-tab-pane>
    </el-tabs>   
    <!-- 创建试卷对话框 -->
    <el-dialog title="创建考试" v-model="createDialogVisible" width="30%">
      <el-form :model="choti" :rules="rules" ref="examForm" label-width="80px" class="custom-form">
        <!-- 试卷名称输入框 -->
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="choti.name" disabled/>
        </el-form-item>
        
        <!-- 考试时间选择器 -->
        <el-form-item label="考试时间" prop="timejilu">
  <el-date-picker
    type="datetimerange"
    start-placeholder="开始时间"
    end-placeholder="结束时间"
    format="YYYY-MM-DD HH:mm:ss"
    value-format="YYYY-MM-DD HH:mm:ss"
    date-format="YYYY/MM/DD ddd"
    time-format="HH:mm:ss"
    :default-time=choti.timejilu
    v-model="choti.timejilu"
  />
</el-form-item>
        <!-- 试卷类型下拉框 -->
        <el-form-item label="试卷类型" prop="leibie">
          <el-select-v2
            v-model="choti.leibie"
            disabled
            :options="initials"
            placeholder="试卷类型"
            clearable
          />
        </el-form-item>
        <!-- 考试班级选择器 -->
        <el-form-item label="考试班级" prop="leibie2">
          <el-select-v2
            multiple
            hide-required-asterisk
            v-model="choti.leibie2"
            :options="banlie"
            :props="{ value: 'class_id', label: 'class_name' }"
            placeholder="选择班级"
            clearable
          />
        </el-form-item>
      </el-form>
      
      <!-- 对话框底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <!-- 取消按钮 -->
          <el-button @click="quxiaoExam">取 消</el-button>
          
          <!-- 确定按钮 -->
          <el-button type="primary" @click="createExam">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { findClassroomByClassId } from "@/api/kaoshi/index";

import { ref, onMounted } from "vue";
import { ElMessage, ElForm } from 'element-plus'
import { findExamInfo, findclass, addExamInfo, deleteExamInfo } from '@/api/kaoshi/kaoguan.js';
import dayjs from "dayjs";
import type { TabsPaneContext } from 'element-plus'


const activeName = ref('first')
const showDialog = ref(false);

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}
const tableData02=ref([])
const zongshuxx=ref(0)
const setexamRoom = async () => {
  let res={
    classId: 0,
    pageNum: 1,
    pageSize: 20
  };
  let data = await findClassroomByClassId(res);
  console.log(data);
  tableData02.value = data.data;
  zongshuxx.value = data.data.length;
};
//查询专业课程
import { direction } from "@/api/common/work/courseManager.js";

// 搜索条件对象
const saosuo = ref({
  xianguan: '',
  leibie: '',
  pageNum: 1,
  pageSize: 10, // 设置为5
  total: 0,
});

const saosuo02 = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  classId:0
});

// 班级列表
const banlie = ref([]);

// 表格数据
const tableData = ref([]);

// 创建试卷对话框显示状态
const createDialogVisible = ref(false);

// 创建试卷表单数据对象
const choti = ref({
  name: '',
  timejilu: [],
  leibie: '',
  paper_id: '',
  leibie2: []
});
const total02 = ref(0);

const setexamRoom02 = async (xx) => {
  // console.log('setexamRoom02');
  // console.log(xx);
  try {
    let data = await findClassroomByClassId(xx);
    console.log(data);
    tableData02.value = data.data;
    saosuo02.value.total = data.data.length;
  } catch (error) {
    console.error("Error fetching exam room data:", error);
  }
};
//考试分页
const handleSizeChange02 = (val: number) => {
  console.log('分页大小:', val);
  saosuo02.value.pageSize = val; // 更新 pageSize
  setexamRoom02(saosuo02.value); // 重新获取考试数据
};

const handleCurrentChange02 = (val: number) => {
  console.log('当前页码:', val);
  saosuo02.value.pageNum = val; // 更新 pageNum
  setexamRoom02(saosuo02.value); // 重新获取考试数据
};
// 删除考试信息操作
const delexam = async (ss) => {
  try {
    await deleteExamInfo(ss); // 假设这是你的删除 API 方法
    ElMessage({
      message: '删除成功',
      type: 'success',
    });
    // 重新获取考试数据
    setexamRoom02(saosuo02.value);
  } catch (error) {
    console.error("Error deleting exam info:", error);
    ElMessage({
      message: '删除失败',
      type: 'error',
    });
  }
};

// 格式化创建时间
const formattedCreateTime = (createTime) => {
  return dayjs(createTime).format('YYYY-MM-DD HH:mm:ss');
};


const formattedCreateTime2 = (createTime) => {
  return dayjs(createTime).format('YYYY-MM-DD HH:mm:ss');
};


// 表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入试卷名称', trigger: 'blur' }
  ],
  timejilu: [
    { required: true, message: '请选择考试时间', trigger: 'change' }
  ],
  leibie2: [
    { required: true, message: '请选择考试班级', trigger: 'change' }
  ]
});

// 获取表单实例
const examForm = ref<InstanceType<typeof ElForm>>();

// 组件挂载时执行的初始化操作
onMounted(() => {
  directionss(); // 获取试卷类型
  banleibie(); // 获取班级列表
  setshuju1(saosuo.value); // 获取试卷数据
  setexamRoom();//获取考场数据
});
const total=ref(0);
// 获取试卷数据
const setshuju1 = async (xx) => {
// console.log(xx);
  let data = await findExamInfo(xx);
  // console.log(data);
  tableData.value = data.data.list;
  saosuo.value.total = data.data.navigatePages;
  // console.log(saosuo.value);
};

// 获取班级列表
const banleibie = async () => {
  let res = await findclass();
  banlie.value = res.data;
};

// 编辑试卷操作
const handleEdit = (index, row) => {
  // console.log('编辑', index, row);
};

// 预览试卷操作
const handleLook = (index, row) => {
  // console.log('预览', index, row);
};

// 创建试卷操作
const handlePreview = (index, row) => {
  // console.log('创建', index, row);
  choti.value.name = row.examination_name;
  createDialogVisible.value = true;
  choti.value.paper_id = row.examination_id;
  choti.value.leibie = row.direction_id;
};
// 修改考场信息
const bianji = (index, row) => {
    // 显示编辑对话框
    createDialogVisible.value = true;

    // 打印日志，输出当前编辑的索引和行数据
    console.log(row);

    // // 将行数据赋值给 choti 对象
    choti.value.name = row.examination_name;
     choti.value.paper_id = row.examination_id;
    choti.value.leibie = row.direction_id;
    choti.value.leibie2 = row.sys_class_id;
     choti.value.timejilu = [
    dayjs(row.start_time).format('YYYY-MM-DD HH:mm:ss'),
    dayjs(row.end_time).format('YYYY-MM-DD HH:mm:ss')
  ];
    console.log(choti.value.timejilu)
    // // 打印 choti 对象以验证赋值结果
    // console.log(choti.value);
}
// 创建考场确认操作
const createExam = async () => {
  examForm.value?.validate(async (valid) => {
    if (valid) {
      let xx = {
        paperId: choti.value.paper_id,
        startTime: choti.value.timejilu[0],
        endTime: choti.value.timejilu[1],
        sysClassId: String(choti.value.leibie2)
      };
      ElMessage({
        message: '创建成功',
        type: 'success',
      });

      let data = await addExamInfo(xx);
      choti.value = {
        name: '',
        timejilu: [],
        leibie: '',
        paper_id: '',
        leibie2: []
      };
      // console.log(data.data);
      createDialogVisible.value = false;
    } else {
      console.log('表单校验失败');
    }
  });
};

//取消创建考场操作
const quxiaoExam = () => {
  choti.value = {
    name: '',
    timejilu: [],
    leibie: '',
    paper_id: '',
    leibie2: []
  };
  createDialogVisible.value = false;
};

// 搜索操作
const performSearch = () => {
  console.log('搜索关键字:', saosuo.value.xianguan);
  console.log('试卷类型:', saosuo.value.leibie);
  setshuju1(saosuo.value);
};

// 分页大小改变时的操作
const handleSizeChange = (val: number) => {
  console.log('分页大小:', val);
  saosuo.value.pageSize = val; // 更新 pageSize
  setshuju1(saosuo.value); // 重新获取试卷数据
};

// 当前页码改变时的操作
const handleCurrentChange = (val: number) => {
  console.log('当前页码:', val);
  saosuo.value.pageNum = val; // 更新 pageNum
  setshuju1(saosuo.value); // 重新获取试卷数据
};

// 试卷类型选项
const initials = ref([]);

// 获取试卷类型
const directionss = async () => {
  try {
    let res = await direction();
    if (res.data) {
      initials.value = res.data.map((item) => ({
        value: item.directionId,
        label: item.directionName,
      }));
    }
  } catch (error) {
    console.error("Error fetching direction:", error);
  }
};
</script>

<style lang="scss" scoped>
.biaoge {
  padding: 16px;
}

.head {
  display: inline-block;
  width: 100%;
  height: 50px;
  line-height: 50px;
  background-color: #f5f5f5;
  border-radius: 5px;
  color: #333;
  font-size: 20px;
  margin-bottom: 16px;
  padding-left: 16px;
  font-weight: 600;
}

.demo-form-inline {
  width: 500px;
  display: flex;
  align-items: center;

  .el-input,
  .el-form-item {
    width: 200px;
    margin-right: 10px;
  }

  .search-button {
    margin-left: 10px;
    height: 30px;
    line-height: 32px;
  }
}

.el-form-item {
    margin-bottom: 20px;

    &__label {
      font-weight: bold;
      color: #606266;
    }

    .el-input,
    .el-select,
    .el-select-v2 {
      width: 100%;
    }
  }

  .el-select-v2,
  .el-select {
    input {
      height: 36px;
      line-height: 36px;
      padding: 0 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
    }

    &:focus-within {
      input {
        border-color: #409eff;
      }
    }
  }
  .button1{
  //隐藏样式
  visibility: hidden;
}
</style> 